using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace EchoFramework
{
    /// <summary>
    /// 事件中心
    /// </summary>
    public class EventCenter
    {
        private static EventCenter instance;
        public static EventCenter Instance
        {
            get
            {
                if (instance == null)
                    instance = new EventCenter();
                return instance;
            }
        }

        private Dictionary<EventType, List<Action<EventObject>>> eventDict = new Dictionary<EventType, List<Action<EventObject>>>();

        /// <summary>
        /// 注册事件
        /// </summary>
        public void Register(EventType type, Action<EventObject> action)
        {
            List<Action<EventObject>> actionList;
            if (eventDict.TryGetValue(type, out actionList))
            {
                if (!actionList.Contains(action))
                {
                    actionList.Add(action);
                }
            }
            else
            {
                actionList = new List<Action<EventObject>>();
                actionList.Add(action);
                eventDict.Add(type, actionList);
            }
        }

        /// <summary>
        /// 执行事件
        /// </summary>
        /// <param name="type"></param>
        /// <param name="objs"></param>
        public void Execute(EventType type, params object[] objs)
        {
            List<Action<EventObject>> actionList;
            if (!eventDict.TryGetValue(type, out actionList))
            {
                Debug.LogWarning(string.Format("事件字典：{0}中的委托事件数量为0！", type));
                return;
            }

            Action<EventObject> eventAction = null;

            for (int i = 0; i < actionList.Count; i++)
            {
                eventAction = actionList[i];
                try
                {
                    eventAction(new EventObject(objs));
                }
                catch (Exception e)
                {
                    Debug.LogWarning(string.Format("执行事件{0}存在问题！", type));
                    Debug.LogWarning(e);
                }
            }
        }

        /// <summary>
        /// 移除事件
        /// </summary>
        public void UnRegiseterByAction(EventType type, Action<EventObject> action)
        {
            List<Action<EventObject>> eventList;
            if (eventDict.TryGetValue(type, out eventList))
            {
                eventList.Remove(action);
            }
        }

        /// <summary>
        /// 移除所有事件
        /// </summary>
        public void UnRegisterAllAction(EventType type)
        {
            List<Action<EventObject>> eventList;
            if (eventDict.TryGetValue(type, out eventList))
            {
                eventList.Clear();
            }
        }
    }
}
